package com.example.mvvmrxjavaokhttpretrofit.base;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.example.mvvmrxjavaokhttpretrofit.net.BaseResponse;

public class BaseActivity extends AppCompatActivity {

    public void registerViewModelObserver(BaseViewModel viewModel) {
//        getLifecycle().addObserver(viewModel);
//        viewModel.setLifecycleTransformer(this.bindToLifecycle());

        viewModel.getErrorLiveData().observe(this, new Observer<BaseResponse<Object>>() {
            @Override
            public void onChanged(@Nullable BaseResponse<Object> stringMyResponse) {
                onApiErrorCallBack(stringMyResponse.getCode(), stringMyResponse.getRepType(),
                        stringMyResponse.getMsg(), stringMyResponse.getData());
            }
        });

        viewModel.getSuccessLiveData().observe(this, new Observer<BaseResponse<Object>>() {
            @Override
            public void onChanged(@Nullable BaseResponse<Object> objectMyResponse) {
                onApiSuccessCallBack(objectMyResponse.getCode(), objectMyResponse.getRepType(),
                        objectMyResponse.getData());
            }
        });

    }

    public <T extends ViewModel> T createViewModel(@NonNull Class<T> modelClass) {
        return ViewModelProviders.of(this).get(modelClass);
    }

    /**
     * 数据请求的错误回调
     *
     * @param responCode 响应码
     * @param responType 接口名
     * @param message    错误描述
     * @param data
     */
    public void onApiErrorCallBack(int responCode, String responType, String message, Object data) {

    }

    /**
     * 数据请求的成功回调
     *
     * @param responCode 响应码
     * @param responType 接口名
     * @param data       View层需要的数据（需要强转数据类型）
     */
    public void onApiSuccessCallBack(int responCode, String responType, Object data) {

    }
}
